import Ember from 'ember';
import {
  modelNameFromRouteName
}
from 'emberworkspace/utils/app-util';

/**
 if mixin target already has same function, target function has high priority.
*/
export default Ember.Mixin.create({
  setupController(controller, model) {
    this.mixinedSetupController(controller, model);
  },
  mixinedSetupController: function(controller, model) {
    controller.set('model', model);
    controller.set('isNewRecord', false); //用来区分是新建还是编辑。
  },
  afterModel: function(model, transition) {
    if (!model.get('isFullLoaded')) {
      transition.abort();
      this.transitionTo(this.get('routeName'), model.get('id'));
    }
  },
  mixinedModel(modelName, params) {
    var store = this.store,
      projection = this.get('projection');

    if (!params.projection && projection) {
      params.projection = projection;
    }

    return store.queryRecord(modelName, params).then(function(md) {
      md.set('isFullLoaded', true);
      if (md.fetched) {
        md.fetched();
      }
      return md;
    });
  },
  model(params) {
    var modelName = modelNameFromRouteName(this.get('routeName'));
    return this.mixinedModel(modelName, params);
  }
});
